<template>
  <common-search
    :show-item="3"
    :col-layout="{ xxl: 6, xl: 8, lg: 8, md: 12, sm: 24, xs: 24 }"
    v-model="query"
    :formItems="formItems"
    @search="onSearch"
    @reset="onReset"
  ></common-search>
  <a-row justify="space-between">
    <a-col :xl="8" :xxl="8" :lg="8" :md="24" :sm="24" :xs="24">
      <a-spin :spinning="pieLoading" size="large">
        <div
          class="line-chart"
          style="border: 1px solid #ccc"
          ref="rankRef"
        ></div>
      </a-spin>
    </a-col>
    <a-col :xl="16" :xxl="16" :lg="16" :md="24" :sm="24" :xs="24">
      <a-spin :spinning="chartLoading" size="large">
        <div
          class="line-chart"
          style="border: 1px solid #ccc; width: 100%"
          ref="truckRankRef"
        ></div>
      </a-spin>
    </a-col>
  </a-row>

  <div style="margin-top: 10px">
    <a-button
      type="primary"
      style="margin-left: 10px"
      @click="exports"
      :loading="exportLoading"
      v-modulePerm="['surveillance:export']"
    >
      <template #icon>
        <ExportOutlined />
      </template>
      明细导出
    </a-button>
    <a-button
      type="primary"
      style="margin-left: 10px"
      @click="imports"
      :loading="importLoading"
      v-modulePerm="['surveillance:export']"
    >
      <template #icon>
        <ImportOutlined />
      </template>
      跟单备注上传
    </a-button>
  </div>

  <common-table
    :columns="columns"
    :dataSource="dataList"
    v-model:localPagination="page"
    @paginationChange="onPageChange"
    v-model:loading="loading"
    :scroll="{ x: 1500, y: 1000 }"
    :slots="['action','logisticsRemark','latestEvent']"
  >
    <template #action="{ record }">
      <a @click="followUp(record)">跟单备注</a>
    </template>
    <template #logisticsRemark="{ record }">
      <a-tooltip>
        <template #title>
          <span style="font-size: 13px;">{{ record.logisticsRemark }}</span>
        </template>
      <span style="overflow: hidden; text-overflow: ellipsis; white-space: nowrap; width: 100%; display: block">
        {{ record.logisticsRemark }}
      </span>
    </a-tooltip>
    </template>
    <template #latestEvent="{ record }">
      <a-tooltip>
        <template #title>
          <span style="font-size: 13px;">{{ record.latestEvent }}</span>
        </template>
        <span style="overflow: hidden; text-overflow: ellipsis; white-space: nowrap; width: 100%; display: block">
        {{ record.latestEvent }}
      </span>
      </a-tooltip>
    </template>
  </common-table>
  <add-form
    :form-item="formItem"
    :title="'跟单备注'"
    :add-form="addForm"
    :ref="addFormRef"
    @submit="submit"
    @close="close"
  />
  <upload-file
    :type="'commPost'"
    :url="'/wms/report_form/batch_update_logistics_remark'"
    :method="'post'"
    :title="'跟单备注上传'"
    ref="upFile"
    @search="search"
  >
    <template #template>
      <a @click="downLoadTemplate">下载模版</a>
    </template>
  </upload-file>
</template>
<script>
export default {
  name: "tail-surveillance",
};
</script>
<script setup>
import CommonSearch from "@/components/commonSearch/index.vue";
import CommonTable from "@/components/commonTable/index.vue";
import { useSearchTable } from "@/hooks/table/useSearchTable";
import { ref, onMounted, watch } from "vue";
import { message } from "ant-design-vue";
import { postFile } from "@utils/service/index.js";
import { getManyDictItems } from "@/api/system/dict.js";
import { useEcharts } from "@/hooks/echarts/useEcharts.js";
import {
  getOverseaExcData,
  getOverseaExcPie,
  getOverseaExcColumn,
  writeLogisticsRemark,
} from "@/api/tail/surveillance.js";
import AddForm from "@/views/upload/components/addForm.vue";
const rankRef = ref();
const truckRankRef = ref();
const columns = ref([]);
const columns1 = ref([
  {
    title: "站点",
    dataIndex: "site",
    key: "site",
    align: "center",
    width: 70,
  },
  {
    title: "仓库",
    dataIndex: "warehouseCode",
    key: "warehouseCode",
    align: "center",
  },
  {
    title: "平台",
    dataIndex: "platform",
    key: "platform",
    align: "center",
    width: 140,
  },
  {
    title: "平台订单",
    dataIndex: "orderId",
    key: "orderId",
    align: "center",
    width: 200,
  },
  {
    title: "物流单",
    dataIndex: "saleOrderCode",
    key: "saleOrderCode",
    align: "center",
    width: 200,
  },
  {
    title: "易仓状态",
    dataIndex: "status_dictText",
    key: "status_dictText",
    align: "center",
  },
  {
    title: "审单时间",
    dataIndex: "pendingTime",
    key: "pendingTime",
    align: "center",
    width: 180,
  },
  {
    title: "已过天数",
    dataIndex: "duration",
    key: "duration",
    align: "center",
    width: 90,
  },
  {
    title: "承运商",
    key: "courierCode",
    dataIndex: "courierCode",
    align: "center",
  },
  {
    title: "跟踪号",
    key: "shippingMethodNo",
    dataIndex: "shippingMethodNo",
    align: "center",
  },
  {
    title: "尾程状态",
    key: "deliveryStatus",
    dataIndex: "deliveryStatus",
    align: "center",
  },
  {
    title: "操作",
    dataIndex: "action",
    key: "action",
    align: "center",
  },
]);
const columns2 = ref([
  {
    title: "站点",
    dataIndex: "site",
    key: "site",
    align: "center",
    width: 70,
  },
  {
    title: "仓库",
    dataIndex: "warehouseCode",
    key: "warehouseCode",
    align: "center",
  },
  {
    title: "平台",
    dataIndex: "platform",
    key: "platform",
    align: "center",
    width: 140,
  },
  {
    title: "平台订单",
    dataIndex: "orderId",
    key: "orderId",
    align: "center",
    width: 200,
  },
  {
    title: "物流单",
    dataIndex: "saleOrderCode",
    key: "saleOrderCode",
    align: "center",
  },
  {
    title: "易仓状态",
    dataIndex: "status_dictText",
    key: "status_dictText",
    align: "center",
  },
  {
    title: "异常信息",
    dataIndex: "errMsg",
    key: "errMsg",
    align: "center",
  },
  {
    title: "异常时间",
    dataIndex: "errTime",
    key: "errTime",
    align: "center",
  },
  {
    title: "操作",
    dataIndex: "action",
    key: "action",
    align: "center",
  },
]);
const columns3 = ref([
  {
    title: "站点",
    dataIndex: "site",
    key: "site",
    align: "center",
    width: 70,
  },
  {
    title: "仓库",
    dataIndex: "warehouseCode",
    key: "warehouseCode",
    align: "center",
  },
  {
    title: "平台",
    dataIndex: "platform",
    key: "platform",
    align: "center",
    width: 140,
  },
  {
    title: "平台订单",
    dataIndex: "orderId",
    key: "orderId",
    align: "center",
    width: 140,
  },
  {
    title: "物流单",
    dataIndex: "saleOrderCode",
    key: "saleOrderCode",
    align: "center",
  },
  {
    title: "物流类型",
    dataIndex: "deliveryType",
    key: "deliveryType",
    align: "center",
  },
  {
    title: "承运商",
    key: "courierCode",
    dataIndex: "courierCode",
    align: "center",
  },
  {
    title: "跟踪号",
    key: "shippingMethodNo",
    dataIndex: "shippingMethodNo",
    align: "center",
  },
  {
    title: "标发时间",
    key: "dateWarehouseShipping",
    dataIndex: "dateWarehouseShipping",
    align: "center",
  },
  {
    title: "已过天数",
    key: "duration",
    dataIndex: "duration",
    align: "center",
  },
  {
    title: "异常信息",
    key: "errMsg",
    dataIndex: "errMsg",
    align: "center",
  },
  {
    title: "异常发生时间",
    key: "errHappenTime",
    dataIndex: "errHappenTime",
    align: "center",
  },
  {
    title: "最近轨迹",
    key: "latestEvent",
    dataIndex: "latestEvent",
    align: "center",
    width: 120
  },
  {
    title: "最近轨迹时间",
    key: "latestEventTime",
    dataIndex: "latestEventTime",
    align: "center",
  },
  {
    title: "跟单备注",
    key: "logisticsRemark",
    dataIndex: "logisticsRemark",
    align: "center"
  },
  {
    title: "操作",
    dataIndex: "action",
    key: "action",
    align: "center",
  },
]);
const formItems = ref([
  {
    label: "站点",
    field: "site",
    type: "select",
    notClear: true,
    options: [],
  },
  {
    label: "异常类型",
    field: "errType",
    type: "select",
    notClear: true,
    options: [],
  },
  {
    label: "已跟单处理",
    field: "isTrackingHandled",
    type: "select",
    options: []
  },
  {
    label: "平台",
    field: "platform",
    type: "select",
    options: [],
  },
  {
    label: "承运商",
    field: "courierCode",
    type: "input",
  },
  {
    label: "仓库",
    field: "warehouseCode",
    type: "input",
  },
  {
    label: "平台订单",
    field: "orderId",
    type: "input",
  },
  {
    label: "易仓订单",
    field: "saleOrderCode",
    type: "input",
  },
]);
const addForm = ref(false);
const addFormRef = ref(null);
const formItem = ref([
  {
    label: "物流单",
    value: "saleOrderCode",
    type: "text",
    defaultValue: "",
  },
  {
    label: "跟单备注",
    value: "logisticsRemark",
    type: "textarea",
    defaultValue: "",
  },
]);
const exportLoading = ref(false);
const pieLoading = ref(false);
const chartLoading = ref(false);
const truckRank = ref([]);
const flag = ref(true);
let instance;
let instance1;
let text = ref("未揽件");
const chartList = ref([]);
const detailChartList = ref([]);
const { dataList, query, loading, search, reset, data, page, onPageChange } =
  useSearchTable({
    searchAPI: getOverseaExcData,
    pageConfig: () => {
      return {
        pageSize: 10,
        pageNo: 1,
        total: 0,
      };
    },
    queryFactory: () => {
      return {
        site: "US",
        errType: "unpick",
      };
    },
    beforeSearch: () => {},
    afterSearch: async () => {
      if (
        query.value.errType === "unpick" ||
        query.value.errType === "notShippingNo"
      ) {
        columns.value = columns1.value;
      } else if (query.value.errType === "defective_shipment") {
        columns.value = columns2.value;
      } else if (query.value.errType === "dispatch_exception") {
        columns.value = columns3.value;
      }
    },
  });
let outerRankInitChart = () => {};
let outerTruckRankInitChart = () => {};
const followUp = (record) => {
  addForm.value = true;
  formItem.value[0].defaultValue = record.saleOrderCode;
  formItem.value[1].defaultValue = record.logisticsRemark
    ? record.logisticsRemark
    : "";
};
const exports = async () => {
  try {
    if (!query.value.site) {
      return message.error("请选择站点和平台");
    }
    if (!query.value.errType) {
      return message.error("请选择异常类型");
    }
    exportLoading.value = true;
    let obj = query.value;
    const res = await postFile(
      "/wms/report_form/unpick_chart_export",
      "post",
      obj,
      `明细导出.xlsx`
    );
    message.success("导出成功");
  } catch (e) {
    message.error(e);
  } finally {
    exportLoading.value = false;
  }
};
const init = async () => {
  try {
    const res = await getManyDictItems({
      dictCodeList: "unpick_chart_site,unpick_chart_errType,platform,boolean_flag",
    });
    formItems.value[0].options = res.result.unpick_chart_site;
    formItems.value[1].options = res.result.unpick_chart_errType;
    formItems.value[2].options = res.result.boolean_flag;
    formItems.value[3].options = res.result.platform;
  } catch (e) {
    console.log(e);
  }
};
const onSearch = async () => {
  if (!query.value.site) {
    return message.error("请选择站点和平台");
  }
  if (!query.value.errType) {
    return message.error("请选择异常类型");
  }
  search();
  switch (query.value.errType) {
    case "unpick":
      text.value = "未揽件";
      break;
    case "notShippingNo":
      text.value = "无跟踪号";
      break;
    case "defective_shipment":
      text.value = "发货问题件";
      break;
    case "dispatch_exception":
      text.value = "派送异常";
      break;
  }
  Promise.all([initChart(), initPieChart()]);
};
const onReset = () => {
  reset();
  Promise.all([initChart(), initPieChart()]);
};
let colorList = {
  US: "#2362c1",
  CA: "#B5C334",
  EU: "#FCCE10",
};
const change = (data, text) => {
  let xData = [];
  let yData = [];
  xData = detailChartList.value.map((item) => item.warehouseCode);
  yData = detailChartList.value.map((item) => item.count);
  return {
    title: {
      text: text.value,
      left: "center",
    },
    grid: {
      left: "3%",
      right: "4%",
      bottom: "3%",
      containLabel: true,
    },
    tooltip: {
      trigger: "item",
    },
    xAxis: [
      {
        type: "category",
        data: xData,
      },
    ],
    yAxis: {
      type: "value",
    },
    series: [
      {
        data: yData,
        itemStyle: {
          normal: {
            color: function (params) {
              return colorList[query.value.site];
            },
          },
        },
        type: "bar",
        label: {
          show: true,
          position: "top",
        },
      },
    ],
  };
};
const changePie = () => {
  return {
    title: {
      text: text.value,
      left: "center",
    },
    tooltip: {
      trigger: "item",
    },
    legend: {
      orient: "vertical",
      left: "left",
    },
    series: [
      {
        type: "pie",
        radius: "70%",
        data: chartList.value?.map((item) => {
          return {
            name: item.site,
            value: item.count,
          };
        }),
        itemStyle: {
          normal: {
            color: function (params) {
              // 返回每个饼图扇区的颜色
              return colorList[params.data.name];
            },
          },
        },
        emphasis: {
          itemStyle: {
            shadowBlur: 10,
            shadowOffsetX: 0,
            shadowColor: "rgba(0, 0, 0, 0.5)",
          },
        },
      },
    ],
  };
};
const initChart = async () => {
  try {
    chartLoading.value = true;
    const res = await getOverseaExcColumn(query.value);
    detailChartList.value = res.result;
    const { initChart: truckRankInitChart } = useEcharts(
      instance1,
      truckRankRef,
      change(truckRank.value, "", query.value.site, flag.value)
    );
    outerTruckRankInitChart = truckRankInitChart;
    if (!flag.value) {
      message.error("暂无数据");
    }
  } catch (e) {
    message.error(e);
  } finally {
    chartLoading.value = false;
  }
};
const initPieChart = async () => {
  try {
    pieLoading.value = true;
    const res = await getOverseaExcPie(query.value);
    chartList.value = res.result;
    const { initChart: rankInitChart } = useEcharts(
      instance,
      rankRef,
      changePie()
    );
    outerRankInitChart = rankInitChart;
  } catch (e) {
    message.error(e);
  } finally {
    pieLoading.value = false;
  }
};
const submit = async (form) => {
  try {
    for (let formKey in form) {
      if (
        form[formKey] === undefined ||
        form[formKey] === null ||
        form[formKey] === "" ||
        form[formKey] == []
      ) {
        delete form[formKey];
      }
    }
    const res = await writeLogisticsRemark(form);
    message.success(`创建成功`);
    await onSearch();
    addForm.value = false;
  } catch (e) {
    message.error(e);
  }
};
const close = () => {
  addForm.value = false;
};

/**上传 */
const upFile = ref();
const importLoading = ref();
const imports = () => {
  upFile.value.handleShow();
};
const downLoadTemplate = async () => {
  try {
    await postFile(
      "/wms/report_form/batch_update_logistics_remark_tpl",
      "get",
      {},
      "跟单备注上传模板.xlsx"
    );
  } catch (e) {
    message.error(e);
  }
};

watch(
  () => detailChartList.value,
  () => {
    outerTruckRankInitChart();
  }
);
watch(
  () => chartList.value,
  () => {
    outerRankInitChart();
  }
);
onMounted(() => {
  init();
  Promise.all([initChart(), initPieChart()]);
});
</script>
<style scoped>
.line-chart {
  width: 90%;
  height: 350px;
}
</style>
